package howl.Servlets;

import howl.model.Model;
import howl.model.PMF;
import howl.types.HowlUser;
import howl.types.query.QueryHelper;
import howl.types.query.ResultSet;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import compiler.exceptions.HowlModelException;

import twitter4j.Twitter;
import twitter4j.TwitterException;

@SuppressWarnings("serial")
public class CSVGenerator extends DataGenerator {
	
	private static int MaxNumberReturned = 100;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		System.out.println(user);
		if (false) {

			resp.sendRedirect(userService.createLoginURL("/Signup.jsp"));

		}else {
			

			/*Query query = pm
					.newQuery("select from howl.HowlUser "
							+ "where users == Param "
							+ "parameters User Param "
							+ "import howl.HowlUser; import com.google.appengine.api.users.User;");

			List<HowlUser> results = (List<HowlUser>) query.execute(user);*/
			
			HowlUser hu = Model.getHowlUserfromUser(user);
			Model m = new Model(hu);
			System.out.println(hu);
			if(hu != null){

				String name = getRequestedURL(req);
				String[] parts = name.split("/");
				name = parts[parts.length-1] ;
				
				name = name.substring(0, name.indexOf("."));
				name = name + "@"+parts[parts.length-2];
				//resp.getWriter().println(name);
				ResultSet rs = QueryHelper.queryByEntity(name, MaxNumberReturned);
				try {
					rs.setTd(m.getTableDescriptor(name));
				} catch (HowlModelException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				resp.getWriter().println(rs.toCSV());	
			}else {
				resp.getWriter().println("You are not authorised to view this page");
				}
			
		}
		
		
	}
	
	
}
